from requests.exceptions import RequestException
from lxml import etree
from bs4 import BeautifulSoup
from pyquery import PyQuery
import requests
import time,json

def clear(content):
	bookname=content.replace("\n","")
	bookname=bookname.replace(" ","")
	bookname=bookname.replace("\\","")
	return bookname

def getPage(url):
    '''爬取指定url地址的信息'''
    try:
        #定义请求头信息
        headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36'}
        #执行爬取
        res = requests.get(url,headers=headers)
        #判断并返回结果
        if res.status_code == 200:
            return res.text
        else:
            return None
    except RequestException:
        return None

def parsePage(content):
    '''解析爬取网页中内容，并返回结果'''
    # print(content)
    #========使用pyquery解析======================
    #初始化，返回Pyquery对象
    doc = PyQuery(content)
    items = doc("tr.item")
    #遍历并解析每部图书具体信息
    for item in items.items():
        yield {
            'name': item.find('td div.pl2 a ').text(),
            'name_other': item.find('td div.pl2 span ').text(),
            'author': item.find('td p.pl ').text(),
            'rating_nums': item.find('td div span.rating_nums').text(),
            'inq': item.find('td p.quote span.inq').text(),
        }

def writeFile(content):
    '''解析爬取网页中内容，并返回结果'''
    with open("./result1.txt",'a',encoding="utf-8") as f:
        f.write(json.dumps(content,ensure_ascii=False)+"\n")

def main(offset):
    '''主程序函数，负责调度执行爬取处理'''
    url = 'https://book.douban.com/top250?start='+str(offset)
    html = getPage(url) #执行爬取
    if html:
        for item in parsePage(html): #执行解析并遍历
            print(item)
            writeFile(item) #执行写操作

#判断当前执行是否为主程序，并遍历调度主函数来爬取信息
if __name__ == '__main__':
    # main(0)
    for i in range(10):
        main(offset=i*25)
        time.sleep(1)
